﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Caam.Framework.Common;
using System.Data;
using System.Text;
using System.IO;
using System.Configuration;

namespace iMenuService
{
    /// <summary>
    /// Summary description for iMenu
    /// </summary>
    [WebService(Namespace = "http://codex13.com.vn/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class iMenu : System.Web.Services.WebService
    {

        [WebMethod(Description = "<i>Lấy thông tin menu và thức ăn/nước uống. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/>&lt;input user=\"lbnam\" pass=\"123456\"/&gt;")]
        [Obsolete("Version 1.0")]

        public string getAll(string input)
        {            
            string result = getCsv(input, "iMenu_usp_Categories_Items_GetAllViaXml");
           
            return result;
        }

        [WebMethod(Description = "<i>Lấy thông tin order sau khi submit. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/>&lt;input user=\"lbnam\" pass=\"123456\"/&gt;")]
        [Obsolete("Version 1.0")]
        public string getOrderList(string input)
        {         
            string result = getCsv(input, "iMenu_usp_Orders_GetListByUser");

            return result;
        }

        [WebMethod(Description = "<i>Submit hóa đơn. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/>&lt;input user=\"lbnam\" pass=\"123456\" note=\"nhanh nhanh\" important=\"1\"/&gt;<br/>"
    + "&lt;items&gt;<br/>"
    + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;item id=\"1\" quantity=\"2\" note=\"\"/&gt;<br/>"
    + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;item id=\"2\" quantity=\"3\" note=\"\"/&gt;<br/>"
    + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;item id=\"4\" quantity=\"6\" note=\"it da\"/&gt;<br/>"
    + "&lt;/items&gt;")]
        [Obsolete("Version 1.0")]
        public string confirmOrder(string input)
        {            
            string result = getCsvScalar(input, "iMenu_usp_Orders_Insert");

            return result;
        }

        private string getCsv(string input, string sp)
        {
            string result = string.Empty;
            try
            {
                DbManager db = new DbManager();
                db.CreateParameters(1);
                db.AddParameter(0, "@input", input);
                DataSet ds = db.ExecuteDataSet(CommandType.StoredProcedure, sp);
                db.Close();
                if (ds != null)
                {
                    result = ConvertDataSetToCSV(ds);
                    if(string.IsNullOrEmpty(result))
                        result = resultToCsv("result", "");
                }
                else
                {
                    result = resultToCsv("result", "");
                }
            }
            catch (Exception ex)
            {
                result = resultToCsv("error", ex.Message);
            }
            return result;
        }

        private string getCsvScalar(string input, string sp)
        {
            string result = string.Empty;
            try
            {
                DbManager db = new DbManager();
                db.CreateParameters(1);
                db.AddParameter(0, "@input", input);
                object obj = db.ExecuteScalarV2(CommandType.StoredProcedure, sp);
                db.Close();
                //if (obj != null)
                //{
                    result = resultToCsv("result", obj);
                //}
            }
            catch (Exception ex)
            {
                result = resultToCsv("error", ex.Message);
            }
            return result;
        }

        [WebMethod(Description = "<i>Lấy url của ảnh trên server. Gọi hàm này xong lấy url ảnh để tải ảnh lưu vào resource. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/>Coffee-icon.png")]
        [Obsolete("Version 1.0")]
        public string getImage(string filename)
        {
            string ret = string.Format("{0}{1}{2}", ConfigurationManager.AppSettings["base_domain"],
                        ConfigurationManager.AppSettings["image_base_path"], "no_image.jpg");

            if (!string.IsNullOrEmpty(filename))
            {
                if (File.Exists(Server.MapPath(ConfigurationManager.AppSettings["image_base_path"] + filename)))
                {
                    ret = string.Format("{0}{1}{2}", ConfigurationManager.AppSettings["base_domain"],
                        ConfigurationManager.AppSettings["image_base_path"], filename);
                }
            }

            ret = resultToCsv("url", ret);
            return ret;
        }

        private string resultToCsv(string name, object value)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("\"{0}\"", name);
            sb.Append(Environment.NewLine);
            sb.Append(value==null?"0": value);
            return sb.ToString();
        }

        protected string ExportDataTableToCSV(DataTable dt)
        {
            //HttpResponse res = HttpContext.Current.Response;
            //res.Clear();
            //res.ContentType = "text/csv";
            //res.AddHeader("content-disposition", "attachment;filename=Categories.csv");

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sb.Append(dt.Columns[i].ColumnName + ',');
            }
            sb.Append(Environment.NewLine);

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    sb.Append(dt.Rows[j][k].ToString() + ',');
                }
                sb.Append(Environment.NewLine);
            }
            //res.Write(sb.ToString());
            return sb.ToString();
            //res.End();
        }

        public static string ConvertDataSetToCSV(DataSet ds)
        {

            const string LC_COMMA = ",";

            const string LC_DBLQUOTE = "\"";

            const string LC_DBLQUOTE_ESC = "\"\"";

            StringBuilder csv = new StringBuilder();

            foreach (DataTable tbl in ds.Tables)
            {

                // Append the table's column headers.

                foreach (DataColumn col in tbl.Columns)
                {

                    csv.Append(LC_DBLQUOTE + col.ColumnName + LC_DBLQUOTE + LC_COMMA);

                }

                csv.Length -= 1;

                csv.Append(Environment.NewLine);

                // Append the table's data.

                foreach (DataRow row in tbl.Rows)
                {

                    foreach (object val in row.ItemArray)
                    {

                        csv.Append(LC_DBLQUOTE + val.ToString().Replace(LC_DBLQUOTE, LC_DBLQUOTE_ESC).Replace(",", ";")

                        + LC_DBLQUOTE + LC_COMMA);

                    }

                    csv.Length -= 1;

                    csv.Append(Environment.NewLine);

                }

                // Add an empty line between this and the next table.

                //csv.Append(Environment.NewLine);
                csv.Append("###");
                csv.Append(Environment.NewLine);

            }

            return csv.ToString();

        }
    }
}
